﻿using IService;
using Microsoft.AspNetCore.Mvc;
using Model;
using Service;
using DAL;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WMS.Controllers
{
    [Route("[controller]")]
    public class OrganizationController : Controller
    {
        private readonly ISysOrganizationService _orgService;
        private readonly IDictService _dictService;
        private readonly AppDbContext _dbContext;

        public OrganizationController(
            ISysOrganizationService orgService,
            IDictService dictService,
            AppDbContext dbContext)
        {
            _orgService = orgService;
            _dictService = dictService;
            _dbContext = dbContext;
        }

        [HttpGet("Index")]
        public IActionResult Index()
        {
            return View();
        }

        #region 数据字典相关方法
        /// <summary>
        /// 获取状态下拉框数据
        /// </summary>
        [HttpGet("dropdown/status")]
        public async Task<IActionResult> GetStatusDropdown([FromQuery] string dictTypeCode = "sys_normal_statu")
        {
            try
            {
                var dictType = await _dictService.GetDictTypeAsync(dictTypeCode);
                if (dictType == null)
                {
                    return Ok(new { code = 200, data = new List<object>(), msg = "字典类型不存在" });
                }

                var statusList = await _dictService.GetDictDataListAsync(dictType.DictTypeId);

                var dropdownData = statusList.Select(d => new
                {
                    value = d.Code,
                    label = d.Name,
                    text = d.Name,
                    disabled = d.Enabled == 0
                }).ToList();

                return Ok(new { code = 200, data = dropdownData, msg = "获取成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 500, msg = "获取状态下拉框失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取多个字典类型的下拉框数据
        /// </summary>
        [HttpGet("dropdown/multiple")]
        public async Task<IActionResult> GetMultipleStatusDropdown([FromQuery] string[] dictTypeCodes)
        {
            try
            {
                var result = new Dictionary<string, object>();

                foreach (var dictTypeCode in dictTypeCodes)
                {
                    var dictType = await _dictService.GetDictTypeAsync(dictTypeCode);
                    if (dictType != null)
                    {
                        var dataList = await _dictService.GetDictDataListAsync(dictType.DictTypeId);
                        var dropdownData = dataList.Select(d => new
                        {
                            value = d.Code,
                            label = d.Name,
                            text = d.Name,
                            disabled = d.Enabled == 0
                        }).ToList();

                        result.Add(dictTypeCode, dropdownData);
                    }
                    else
                    {
                        result.Add(dictTypeCode, new List<object>());
                    }
                }

                return Ok(new { code = 200, data = result, msg = "获取成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 500, msg = "获取多字典下拉框失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取"基本状态"的字典项
        /// </summary>
        [HttpGet("dict/status")]
        public async Task<IActionResult> GetStatusDict()
        {
            try
            {
                var dictType = await _dictService.GetDictTypeAsync("sys_normal_statu");
                if (dictType == null)
                {
                    return Ok(new { code = 200, data = new List<WmsDictData>(), msg = "字典类型不存在" });
                }

                var statusList = await _dictService.GetDictDataListAsync(dictType.DictTypeId);
                return Ok(new { code = 200, data = statusList, msg = "获取成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 500, msg = "获取状态字典失败", error = ex.Message });
            }
        }

        [HttpGet("test")]
        public IActionResult Test()
        {
            return Ok(new
            {
                code = 200,
                msg = "OrganizationController is working!",
                timestamp = DateTime.Now,
                serviceStatus = _dictService != null ? "DictService is injected" : "DictService is null"
            });
        }
        #endregion

        #region 组织机构CRUD操作
        /// <summary>
        /// 获取所有组织机构
        /// </summary>
        [HttpGet("list")]
        public async Task<IActionResult> GetAll()
        {
            try
            {
                var list = await _orgService.GetAllAsync();
                return Ok(new { code = 200, data = list });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 500, msg = "服务器内部错误", error = ex.Message });
            }
        }

        /// <summary>
        /// 按条件查询组织机构
        /// </summary>
        [HttpGet("query")]
        public async Task<IActionResult> Query([FromQuery] string keyword, [FromQuery] string status)
        {
            try
            {
                var list = await _orgService.QueryAsync(keyword, status);
                return Ok(new { code = 200, data = list });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 500, msg = "查询失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 根据ID获取组织机构
        /// </summary>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetById(long id)
        {
            try
            {
                var org = await _orgService.GetByIdAsync(id);
                if (org == null)
                {
                    return NotFound(new { code = 404, msg = "组织机构不存在" });
                }
                return Ok(new { code = 200, data = org });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 500, msg = "获取详情失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 新增组织机构
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Add([FromBody] SysOrganization organization)
        {
            try
            {
                // 添加详细的请求数据日志
                Console.WriteLine($"=== 新增组织请求开始 ===");
                Console.WriteLine($"收到组织数据: OrgId={organization.OrgId}");
                Console.WriteLine($"OrgCode={organization.OrgCode}");
                Console.WriteLine($"OrgShortName={organization.OrgName}");
                Console.WriteLine($"OrgLevel={organization.OrgLevel}");
                Console.WriteLine($"ParentOrgId={organization.ParentOrgId}");
                Console.WriteLine($"OrgStatus={organization.OrgStatus}");
                Console.WriteLine($"OrgRemark={organization.OrgRemark}");

                var success = await _orgService.AddAsync(organization);

                if (!success)
                {
                    Console.WriteLine("新增组织失败：服务层返回false");
                    return Ok(new { code = 400, success = false, msg = "新增失败，请检查数据" });
                }

                Console.WriteLine($"=== 新增组织成功，新组织ID: {organization.OrgId} ===");
                return Ok(new { code = 200, success, msg = "新增成功" });
            }
            catch (ArgumentException argEx)
            {
                // 参数验证错误
                Console.WriteLine($"参数验证失败: {argEx.Message}");
                return BadRequest(new { code = 400, success = false, msg = argEx.Message });
            }
            catch (DbUpdateException dbEx)
            {
                // 数据库更新异常
                Console.WriteLine($"数据库更新异常: {dbEx.Message}");
                var innerMsg = dbEx.InnerException?.Message ?? "";
                Console.WriteLine($"内部异常: {innerMsg}");

                if (innerMsg.Contains("UNIQUE") || innerMsg.Contains("unique") || innerMsg.Contains("重复"))
                {
                    return BadRequest(new { code = 400, success = false, msg = "组织编号已存在，请使用其他编号" });
                }
                else if (innerMsg.Contains("FOREIGN") || innerMsg.Contains("foreign"))
                {
                    return BadRequest(new { code = 400, success = false, msg = "上级组织不存在" });
                }
                else if (innerMsg.Contains("cannot insert null") || innerMsg.Contains("NOT NULL"))
                {
                    return BadRequest(new { code = 400, success = false, msg = "缺少必需的字段数据" });
                }
                else
                {
                    return StatusCode(500, new
                    {
                        code = 500,
                        success = false,
                        msg = "数据库保存失败",
                        error = innerMsg,
                        fullError = dbEx.ToString()
                    });
                }
            }
            catch (Exception ex)
            {
                // 记录详细错误信息
                Console.WriteLine($"新增组织异常：{ex.Message}");
                Console.WriteLine($"堆栈跟踪：{ex.StackTrace}");
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"内部异常：{ex.InnerException.Message}");
                    Console.WriteLine($"内部异常堆栈：{ex.InnerException.StackTrace}");
                }

                return StatusCode(500, new
                {
                    code = 500,
                    success = false,
                    msg = "新增失败",
                    error = ex.Message,
                    innerError = ex.InnerException?.Message,
                    stackTrace = ex.StackTrace
                });
            }
        }

        /// <summary>
        /// 编辑组织机构
        /// </summary>
        [HttpPut]
        public async Task<IActionResult> Update([FromBody] SysOrganization organization)
        {
            try
            {
                var success = await _orgService.UpdateAsync(organization);
                return Ok(new { success, msg = success ? "编辑成功" : "编辑失败" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { success = false, msg = "编辑失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 删除组织机构
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(long id)
        {
            try
            {
                var success = await _orgService.DeleteAsync(id);
                return Ok(new { code = 200, success, msg = success ? "删除成功" : "删除失败" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 500, msg = "删除失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 批量删除组织机构
        /// </summary>
        [HttpPost("batch-delete")]
        public async Task<IActionResult> BatchDelete([FromBody] List<long> ids)
        {
            try
            {
                var success = await _orgService.BatchDeleteAsync(ids);
                return Ok(new { code = 200, success, msg = success ? "批量删除成功" : "批量删除失败" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 500, msg = "批量删除失败", error = ex.Message });
            }
        }
        #endregion

        /// <summary>
        /// 校验组织编号是否已存在
        /// </summary>
        [HttpGet("check-code")]
        public async Task<IActionResult> CheckCodeExists([FromQuery] string code)
        {
            try
            {
                var exists = await _orgService.CheckCodeExistsAsync(code);
                return Ok(new { exists, code = 200, msg = "校验成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 500, msg = "校验失败", error = ex.Message });
            }
        }
        /// <summary>
        /// 编辑时，根据上级组织ID生成当前组织的编号
        /// </summary>
        [HttpGet("generate-code-by-parent")]
        public async Task<IActionResult> GenerateCodeByParent([FromQuery] long parentOrgId)
        {
            try
            {
                // 1. 获取上级组织信息
                var parentOrg = await _orgService.GetByIdAsync(parentOrgId);
                if (parentOrg == null)
                {
                    return BadRequest(new { code = 400, msg = "上级组织不存在" });
                }

                // 2. 提取上级组织的org_code作为前缀（可根据业务规则截取，这里直接用完整编号作为前缀）
                // 例如：上级org_code为"FT001"，前缀为"FT"；若上级是"CG"，前缀为"CG"
                string prefix = parentOrg.OrgCode;
                // （可选）如果前缀需要固定长度，可截取：prefix = parentOrg.OrgCode.Substring(0, 2);

                // 3. 调用已有的编号生成方法
                string newOrgCode = await _orgService.GenerateOrgCodeAsync(prefix);

                return Ok(new { code = 200, data = newOrgCode, msg = "编号生成成功" });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 500, msg = $"生成编号失败：{ex.Message}" });
            }
        }
    }
}